package com.family.pedigree.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.family.pedigree.domain.FamilyNode;
import com.family.pedigree.mapper.FamilyNodeMapper;
import com.family.pedigree.service.IFamilyNodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 家族数节点信息 服务实现类
 * </p>
 *
 * @author forever
 * @since 2024-11-10
 */
@Service
public class FamilyNodeServiceImpl extends ServiceImpl<FamilyNodeMapper, FamilyNode> implements IFamilyNodeService {

    @Override
    public void add(FamilyNode familyNode) {
        //校验主次,如果是次,则必须有关联id(例:添加妻子,则关联id是丈夫)
        if ("1".equals(familyNode.getIsMain())) {
            if (familyNode.getRelatedId() != null && StringUtils.isNotBlank(familyNode.getSpouse())) {
                throw new RuntimeException("配偶信息不能为空,或配偶名称不能为空");
            }
            FamilyNode primary = getById(familyNode.getNodeId());
            if (Objects.isNull(primary)) throw new RuntimeException("当前主的信息不存在,请重新选择");
            save(familyNode.setCreateBy("admin").setCreateTime(LocalDateTime.now()).setUpdateBy("admin")
                    .setUpdateTime(LocalDateTime.now()));
            System.out.println(familyNode.getNodeId());
            //更新主的配偶信息
            updateById(primary.setRelatedId(familyNode.getNodeId())
                    .setSpouse(familyNode.getNodeName())
                    .setImageSpouse(familyNode.getImageSelf())
                    .setUpdateBy("admin")
                    .setUpdateTime(LocalDateTime.now()));

        }
        //如果是主,就直接保存
        save(familyNode.setCreateBy("admin").setUpdateBy("admin").setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now()));
    }


    @Override
    public void edit(FamilyNode familyNode) {
        verifyNode(familyNode);
        updateById(familyNode);
    }

    private void verifyNode(FamilyNode node) {
        if (node.getNodeId() == null) throw new RuntimeException("id不能为空");
        FamilyNode current = getById(node.getNodeId());
        if (Objects.isNull(current)) throw new RuntimeException("查无此信息");
        if (StringUtils.isNotBlank(node.getIsMain()))
            throw new RuntimeException("不能修改主次");
        if (node.getFamilyRank() != null)
            throw new RuntimeException("不能修改代级");
    }

    @Override
    public void delById(Long nodeId) {
        //todo:无权限的不能删除
        //有子节点不能删除
        Long count = baseMapper.selectCount(Wrappers.<FamilyNode>lambdaQuery()
                .eq(FamilyNode::getFamilyId, nodeId));

        if (count > 0) {
            throw new RuntimeException("有子节点,不能删除");
        }
        updateById(getById(nodeId).setIsDelete(1));

    }
}
